from os import listdir
from os.path import join, dirname

from django.shortcuts import render_to_response, get_object_or_404
from django.http import Http404

from vcs.models import Repository, Branch, Commit


def repository_list(request):
    return render_to_response('vcs/repository_list.html', {
        'repositories': Repository.objects.all()
    })

def repository_detail(request, repository):
    return render_to_response('vcs/repository.html', {
        'r': get_object_or_404(Repository, name=repository)
    })

def branch_detail(request, repository, branch):
    return render_to_response('vcs/branch.html', {
        'b': get_object_or_404(Branch, repository__name=repository, name=branch)
    })

def commit_detail(request, repository, branch, commit):
    try:
        branch = get_object_or_404(Branch, repository__name=repository,
            name=branch)
        c = branch.commits.get(identifier=commit)
        return render_to_response('vcs/commit.html', {
            'c': c
        })
    except Commit.NotFound:
        raise Http404

def populate_with_test_fixtures(request):
    repos = []
    if request.POST:
        repo_root = join(dirname(__file__), 'fixtures/repositories/svn')
        for repo in listdir(repo_root):
            r = Repository.objects.get_or_create(
                repository_type='svn',
                name=repo,
                url='file://' + join(repo_root, repo),
            )[0]
            r.refresh()
            repos.append(r)
    return render_to_response('vcs/populate_fixtures.html', {'repos': repos})
